/*
 * name: server
 * version: 0.3.0
 * update: 百度地址反查支持静默
 * date: 2015-12-16
 */

define(function(require, exports, module) {
	"use strict";

	require('box');
	//资源路径处理
	var _source = function(source, host) {
		if (!$.trim(source)) {
			return "";
		};
		// host = host && host.split ? host : appcfg.host.source;
		// if(/^([\w-]+:)?\/\/([^\/]+)/.test(source)){
		// 	source = host + source.replace(/^([\w-]+:)?\/\/([^\/]+)/,'');
		// }

		return source;
	};
	var _getDate = function(source, ignore_minute) {
		if (source && isNaN(Number(source))) {
			return source.slice(0, 16);
		}
		var myDate = source ? new Date(Number(source)) : new Date();
		var separate = '-';
		var minute = '';
		if (!ignore_minute) {
			minute = (myDate.getHours() < 10 ? " 0" : " ") + myDate.getHours() + ":" + (myDate.getMinutes() < 10 ? "0" : "") + myDate.getMinutes();
		}
		return myDate.getFullYear() + separate + (myDate.getMonth() + 1) + separate + (myDate.getDate() < 10 ? '0' : '') + myDate.getDate() + minute;
	};
	//xss过滤
	etpl.addFilter('xss', function(source) {
		return _xss(source);
	});
	//日期格式化
	etpl.addFilter('date', function(source, ignore_minute) {
		return _getDate(source, ignore_minute);
	});
	//图片域名处理
	etpl.addFilter('source', function(source, host) {
		return _source(source, host);
	});
	//货币小数点
	etpl.addFilter('decimal', function(source, index) {
		var num = parseFloat(source),
			i = index ? index : 1;
		if (isNaN(num)) {
			return source;
		}
		return num.toFixed(i);
	});

	etpl.addFilter('richMedia', function(source, replace) {
		return _richMedia(source, replace);
	});
	//xss过滤
	var _xss = function(source) {
		var ignoreStyle = ['text-align: center;', 'text-indent: 2em;'];
		return filterXSS(source, {
			onIgnoreTagAttr: function(tag, name, value, isWhiteAttr) {
				var result = '';
				if (tag == 'table' && name == 'class') {
					result += ('class="' + value + ' table-bordered"');
				}
				if (name == 'style') {
					var _styleStr = '';
					$.each(ignoreStyle, function(i, e) {
						if (value.indexOf(e) > -1) {
							_styleStr += e
						}
					});
					if ($.trim(_styleStr)) {
						result += (' style="' + _styleStr + '"');
					}
				}
				return result;
			}
		});
	};
	//富媒体消息解析
	var _richMedia = function(source, replace) {
		var checkImg = function(source) {
			var dom = $.parseHTML(source),
				result = "";
			$(dom).find('img').addClass('ableOpenImg');
			$(dom).each(function(i, e) {
				if ($.trim(e.innerHTML)) {
					result += e.outerHTML
				}
			});
			//console.log(result)
			return result;
		}
		var checkLink = function(source) {
			var dom = $.parseHTML(source),
				result = "";
			$(dom).find('a[href]').each(function(i, e) {
				var url = $(e).attr('href');
				if (url.indexOf('http') == 0) {
					$(e).removeAttr('href').addClass('openView').attr('data-view', '2,' + url);
				}

			});
			$(dom).each(function(i, e) {
				if ($.trim(e.innerHTML)) {
					result += e.outerHTML
				}
			});
			//console.log(result)
			return result;
		};
		var checkTel = function(source) {
			if (replace) {
				replace = '【电话】';
			}
			var img = /\[tel\](.*?)\[tel\]/,
				res,
				check = function() {
					if (img.test(source)) {
						res = img.exec(source);
						source = source.replace(res[0], replace ? replace : '<a href="tel:' + res[1] + '" class="btn btn-link">' + res[1] + '</a>');
						check(source);
					}
				};
			check(source);
			return source;
		}
		var _;
		_ = checkImg(source);
		_ = checkLink(_);
		_ = checkTel(source);
		return _;
	};
	etpl.addFilter('_checkTel', function(source, replace) {
		return _checkTel(source, replace);
	});

	//加密手机号
	var _secMobile = function(m) {
		if (m) {
			m = String(m);
		}
		if (m.length == 11) {
			return m.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		}
	};
	//退出登录
	var _logout = function() {
		//appcan.ls.remove('appInit');
		appcan.ls.remove('user');
		//清空推送别名和标签
		if (window.uexJPush) {
			uexJPush.setAliasAndTags(JSON.stringify({
				alias: "",
				tags: []
			}));
		} else if (window.uexXGPush) {
			//注册设备并解除本设备绑定的账号
			uexXGPush.registerPush("*");
			uexXGPush.delTag('user');
		};
		appcan.openView({
			anim: 4,
			param: 'changeuser'
		}, 'member', 'login');
	};
	//发短信
	var sendMsgWaitTime,
		sendMsgTimer;
	var _sendMsg = function(m, logSendMsg, callback) {
		sendMsgWaitTime = 60;
		sendMsgTimer && clearInterval(sendMsgTimer);
		if (!m) {
			return;
		}
		if ($('#getCode').hasClass('unable')) {
			return
		};
		$('#getCode').addClass('unable');
		appcan.loading.show();
		appcan.ajax({
			url: appcfg.host.control + '/core/logSendMsg.jsp',
			data: {
				usern: m,
				sid: appcfg.project.sid
			},
			timeout: appcfg.set.msgtime,
			cache: false,
			success: function(res) {
				appcan.loading.hide();
				if (res.status === 'Y') {
					var ot = $('#getCode').text();
					sendMsgTimer = setInterval(function() {
						sendMsgWaitTime--;
						$('#getCode').text(sendMsgWaitTime + 's后再次发送');
						if (!sendMsgWaitTime) {
							$('#getCode').removeClass('unable').text(ot);
							typeof(callback) === 'function' && callback();
							clearInterval(sendMsgTimer);
						}
					}, 1000);
				} else if (res.message) {
					$('#getCode').removeClass('unable');
					$.box.msg(res.message, {
						delay: 2000
					});
				}
			},
			error: function() {
				$('#getCode').removeClass('unable');
				appcan.loading.hide();
				clearInterval(sendMsgTimer);
				appcan.window.openToast('获取失败请重试！', 2000, 5);
			}
		});
	};

	//存储用户信息
	var _initUser = function(userData) {
		if ($.trim(userData['headImg']) == '') {
			userData.headImg = '';
		} else {
			userData.headImg = _source(userData.headImg);
		}
		if ($.trim(userData['nickName']) == '') {
			userData.nickName = '会员_' + parseInt(Math.random() * 10000);
		}
		if ($.trim(userData['nowScore']) == '') {
			userData.nowScore = 0;
		}
		if ($.trim(userData['realName']) == '') {
			userData.realName = '';
		}
		appcan.ls.val('user', JSON.stringify(userData));
		//app初始化
		appcan.ls.val('appInit', 1);
		//注册推送
		if (window.uexJPush) {
			//设置tag
			uexJPush.setTags(JSON.stringify({
				tags: ["user"]
			}));
			//设置推送别名
			uexJPush.setAlias(JSON.stringify({
				alias: "user_" + userData.id
			}));
		} else if (window.uexXGPush) {
			//注册并绑定别名
			uexXGPush.onRegisterCb = function(opCode, dataType, data) {
				if (opCode == 0) {
					appcan.logfile("信鸽推送注册成功，token为：" + data);
				} else {
					appcan.logfile("注册失败，错误码：" + opCode + "，错误信息：" + data);
				}
			}
			uexXGPush.registerPush("user_" + userData.id);
			//tag
			uexXGPush.setTag('user');
		}
	};
	//获取用户信息
	var _getUser = function(hold) {
		var _user = appcan.ls.val('user');
		if (_user) {
			_user = JSON.parse(_user);
		} else if (!hold) {
			return $.box.alert('请先登录！', function() {
				appcan.openView(null, 'member', 'login');
			}, {
				bgclose: false
			});
		}
		return _user;
	};
	//百度坐标反查
	var _getAddrByLoc = function(lat, lng, config) {
		var def = {
			gps: false,
			callback: null,
			silent: false
		}
		var opt = $.extend(def, config || {});
		if (!opt.silent) {
			appcan.loading.show('正在检索地址...');
		}

		//默认百度坐标
		var coordtype = 'bd09ll';
		// gps设备坐标
		if (opt.gps) {
			coordtype = 'wgs84ll';
		};
		$.ajax({
			url: 'http://api.map.baidu.com/geocoder/v2/',
			dataType: 'jsonp',
			data: {
				ak: appcfg.plugin.bdmap.key,
				coordtype: coordtype,
				location: lat + ',' + lng,
				output: 'json',
				pois: 1
			},
			success: function(res) {
				if (res.status == 0) {
					if (typeof(opt.callback) === 'function') {
						opt.callback(res);
					}
				} else {
					appcan.loading.hide();
					appcan.window.openToast('baiduMap geocoder API错误,code:' + res.status, 2000, 5);
				}
			}
		});
	};
	//回传用户注册地
	var _uploadifyLocation = function() {
		var hasLocat;
		var userData = _getUser();
		var updateUser = function(location) {
			appcan.ajax({
				url: appcfg.host.control + '/member/modifyUserInfo.jsp',
				data: {
					"sid": appcfg.project.sid,
					"member_id": userData.id,
					"province": location.province,
					"city": location.city,
					"area": location.district
				},
				success: function(res) {
					if (res.status === 'Y') {

					} else {
						//alert(res.message)
					}
				},
				error: function() {
					appcan.logfile('回传用户地理位置时发生错误');
				}
			});
		};
		_getLocation(function(lat, lng) {
			_getAddrByLoc(lat, lng, {
				silent: true,
				callback: function(res) {
					var locObj = res.result.addressComponent;
					var location = {};
					location.lng = lng;
					location.lat = lat;
					location.province = locObj.province;
					location.city = locObj.city;
					location.district = locObj.district;
					location.formatted_address = res.result.formatted_address;
					updateUser(location);
				}
			});
		});
	};
	//收集信息
	var _collection = function() {
		var oldInfo = JSON.parse(appcan.ls.val('DeviceInfo')) || {},
			newInfo = {},
			send = function(extraParam) {
				var userData = JSON.parse(appcan.ls.val('user')),
					hasChange;
				extraParam.saveDate = _getDate(false, true);
				//日期过滤
				if (oldInfo['saveDate'] && oldInfo['saveDate'] >= extraParam.saveDate) {
					return
				}
				//信息改变过滤
				$.each(extraParam, function(i, e) {
					if (e !== oldInfo[i]) {
						hasChange = true;
						return
					}
				});
				if (hasChange && $.isPlainObject(userData)) {
					appcan.ls.val('DeviceInfo', JSON.stringify(extraParam));
					var data = $.extend({
						sid: appcfg.project.sid,
						member_id: userData.id
					}, extraParam);
					appcan.ajax({
						url: appcfg.host.control + '/member/loginLog.jsp',
						data: data,
						success: function(res) {

						},
						error: function() {
							appcan.logfile('回传设备信息时发生错误');
						}
					});
				};
			};
		appcan.device.getDeviceInfo(function(deviceInfo, singleInfo, i, len, completeCount) {
			newInfo.app_version = appcfg.set.version;
			newInfo.os = deviceInfo['os'];
			newInfo.manufacturer = deviceInfo['manufacturer'];
			newInfo.device_type = deviceTypeHash[deviceInfo['deviceType']];
			newInfo.connect_status = netHash[deviceInfo['connectStatus']];
			newInfo.mobile_operator_name = deviceInfo['mobileOperatorName'];
			newInfo.model = deviceInfo['model'];
			newInfo.resolution_ratio = deviceInfo['resolutionRatio'];
			_getLocation(function(lat, lng) {
				newInfo.latitude = lat;
				newInfo.longitude = lng;
				send(newInfo);
			}, function() {
				send(newInfo);
			});
		});
	};
	//计数器
	var syncNumByInput;
	var pro_counter_func = function(e) {
		var target = $(e.target);
		//计数器减
		if (target.is('.pro_counter_reduce') || target.parents('.pro_counter_reduce').length) {
			e.preventDefault();
			if (target.parents('.pro_counter_reduce').length) {
				target = target.parents('.pro_counter_reduce');
			}
			var _input = target.parent().find('.pro_counter_val'),
				_min = target,
				_plus = target.parent().find('.pro_counter_add'),
				_max = _input.data('max') ? Number(_input.data('max')) : Number.POSITIVE_INFINITY,
				minBuyCount = target.data('minbuycount') || 1;

			if (target.hasClass('disabled') || target.parents('.list').hasClass('nostore')) {
				return;
			};
			if (parseInt(_input.val()) <= (1 + minBuyCount)) {
				_input.val(minBuyCount);
				_min.addClass('disabled');
				_plus.removeClass('disabled');
			} else {
				_input.val(parseInt(_input.val()) <= _max ? (parseInt(_input.val()) - minBuyCount) : _max);
				_plus.removeClass('disabled');
				target.parents('.list').removeClass('noenough');
			};
			syncNumByInput(_input);
		};
		//计数器增加
		if (target.is('.pro_counter_add') || target.parents('.pro_counter_add').length) {
			e.preventDefault();
			if (target.parents('.pro_counter_add').length) {
				target = target.parents('.pro_counter_add');
			}
			var _input = target.parent().find('.pro_counter_val'),
				_min = target.parent().find('.pro_counter_reduce'),
				_plus = target,
				_max = _input.data('max') ? Number(_input.data('max')) : Number.POSITIVE_INFINITY,
				minBuyCount = target.data('minbuycount') || 1;
			if (target.hasClass('disabled') || target.parents('.list').hasClass('nostore')) {
				return;
			};
			if (parseInt(_input.val()) < _max - minBuyCount) {
				_input.val(parseInt(_input.val()) + minBuyCount);
				_min.removeClass('disabled');

			} else {
				_input.val(_max);
				_plus.addClass('disabled');
				_min.removeClass('disabled');
				target.parents('.list').removeClass('noenough');

			};
			syncNumByInput(_input);
		}
	};
	var pro_counter_inp = function(e) {
		var target = $(e.target);
		//计数器输入框
		var _input = target,
			_min = target.parent().find('.pro_counter_reduce'),
			_plus = target.parent().find('.pro_counter_add'),
			_max = _input.data('max') ? Number(_input.data('max')) : Number.POSITIVE_INFINITY,
			_val = isNaN(parseInt(_input.val())) ? 0 : parseInt(_input.val());
		if (target.parents('.list').hasClass('nostore')) {
			return
		};
		if (_val <= 1) {
			_input.val('1');
			_min.addClass('disable');
			target.parents('.list').removeClass('noenough');
		} else if (_val >= _max) {
			_input.val(_max);
			_plus.addClass('disable');
		} else {
			_min.removeClass('disable');
			_plus.removeClass('disable');
			target.parents('.list').removeClass('noenough');
		};
		syncNumByInput(_input);

	};
	var _proCounter = function(callback) {
		if (typeof(callback) === 'function') {
			syncNumByInput = callback;
		} else {
			syncNumByInput = function(inp) {
				var _num = inp.val(),
					_shopCheckbox = inp.parents('.item').find('._shopCheckbox');
				_shopCheckbox.data('num', _num);
			}
		}
		$('body').unbind('click', pro_counter_func).unbind('blur', '.pro_counter_val', pro_counter_inp);
		$('body').on('click', pro_counter_func).on('blur', '.pro_counter_val', pro_counter_inp);
	};
	//数据预取
	var _preGet = function(cb) {
		var got = 0,
			preGetList = _preGet.prototype.preGetList,
			getOne = function() {
				got++;
				if (got >= preGetList.length && typeof(cb) === 'function') {
					cb();
					got = null;
					getOne = null;
					preGetList = null;
				}
			};
			
		//开始加载
		$.each(preGetList,function(i,e){
			appcan.ajax({
				url: e.url,
				data: e.data,
				success: function(res) {
					getOne();
					if (res.status === 'Y') {
						var data = res.data;
						if(data.split){
							data = JSON.parse(data);
						}
						appcan.ls.val(e.key, JSON.stringify(data));
					}
				},
				error: function() {}
			});
		});
	};
	_preGet.prototype.preGetList = [];
	//预取配置信息
	_preGet.prototype.preGetList.push({
		key:'websiteConfig',
		url:appcfg.host.control + '/core/websiteConfig.jsp',
		data: {
			sid:appcfg.project.sid
		}
	});
	//预取产品类别
	_preGet.prototype.preGetList.push({
		key:'partcat',
		url:appcfg.host.control + '/core/getpartcat.jsp',
		data: {
			sid:appcfg.project.sid
		}
	});
	//预取数据
	var _checkPreget = function(){
		var preGetList = _preGet.prototype.preGetList,
			isDone = true;
		$.each(preGetList,function(i,e){
			if(!appcan.ls.val(e['key'])){
				_preGet();
				isDone = false;
				return false;
			};
		});
		return isDone;
	};
	//处理推送
	var _catchPush = function(data) {
		//关闭消息管理
		return null;
		var userId = _getUser('hold')['id'] || 'nobody';
		//debug
		// var testdata = '{"msgId":"1363854126","content":"发送测试","notificationId":1363854126,"title":"智慧重汽","extras":{"date":"2015-12-09 23:23","type":"message"}}'
		// data = testdata;
		if (data.split) {
			data = JSON.parse(data);
		}
		if (data['extras']) {
			//标题
			if (data['extras']['type']) {
				switch (data['extras']['type']) {
					case "message":
						data['title'] = "通知消息"
						break;
					case "order":
						data['title'] = "订单消息"
						break;
					case "serverform":
						data['title'] = "服务消息"
						break;
				}
			}
			//日期
			if (data['extras']['date']) {
				data.date = data['extras']['date'];
			}

		};
		//内容
		if (!data['content']) {
			if (data['message']) {
				data['content'] = data['message']
			} else {
				data['content'] = '';
			}
		};

		appcan.window.publish('newmsg', 1);
	};
	//检查升级
	var _checkUpdate = function(platform, silence) {
		var appVersion = appcfg.set.version;
		if (!appVersion) {
			appVersion = 0;
		};
		$.ajax({
			url: appcfg.host.control + '/core/checkUpdate.jsp',
			dataType:'json',
			cache: false,
			success: function(res) {
				appcan.loading.hide('puload');
				if (res.version > appVersion) {
					if (silence && res.forceUpdate != '1') {
						appcan.window.publish('newVersion', res.version);
					} else {
						var uploadbox = $.box.confirm(res.description, function() {
							$.box.hide(uploadbox);
							if (platform == 'ios') {
								window.location = res.iosPath;
							} else if (platform == 'android') {
								window.location = res.androidPath;
							}
						}, null, {
							bar: true,
							title: '升级到 V' + res.version
						});
					}
				} else {
					if (!silence) {
						appcan.window.openToast('已是最新版本。', 1000, 5);
					}

				}
			},
			error: function() {
				if (!silence) {
					appcan.loading.hide('puload');
					appcan.window.openToast('网络错误，暂时无法检测更新！', 1000, 5);
				}
			}
		});
	};
	//指定DOM打开地图
	var _openBaiduMap = function(dom, data, refresh) {
		if (!data['longitude'] || !data['latitude']) {
			return appcan.window.openToast('参数缺失，无法打开地图');
		}
		var bdMapParam = {
			lat: data['latitude'],
			lng: data['longitude'],
			loctype: data['loctype'] || 'gps',
			markName: data['name'] || ''
		};
		appcan.ls.val('bdMapData', JSON.stringify(bdMapParam));
		if (refresh) {
			appcan.window.evaluatePopoverScript('', 'bdMapView', 'refresh()');
		} else {
			setTimeout(function() {
				appcan.window.popoverElement({
					id: dom,
					name: 'bdMapView',
					url: seajs.root + '/view/common/baiduMap/temp.html',
					top: parseInt(window.selfTop) + $("#" + dom).offset().top
				});
			}, 0);
		}
	};
	//公用模板
	var _commonTemp = function(tempName, data) {
		var data = data || {};
		var etplEngine = new etpl.Engine();
		var template = appcan.ls.val('template');
		if (!template) {
			appcan.ajax({
				type: 'get',
				url: seajs.root + '/temp/template.html',
				dataType: 'html',
				async: false,
				cache:false,
				success: function(res) {
					template = res;
					appcan.ls.val('template', res);
				},
				error: function() {
					appcan.window.openToast('公共模板加载出错');
				}
			});
		}
		etplEngine.compile(template);
		var Render = etplEngine.getRenderer(tempName);
		var Html = Render(data);
		return Html;
	};
	//获取地理位置
	var _getLocation = function(callback, errcb) {
		//获取地址
		var hasLocat = true;
		if (window.uexLocation) {
			var chaoshi = setTimeout(function() {
				appcan.loading.hide();
				if (appcan.ls.val('gps')) {
					var gpsCache = JSON.parse(appcan.ls.val('gps'));
					typeof(callback) === 'function' && callback(gpsCache.lat, gpsCache.lng);
				} else {
					if (errcb && typeof(errcb) === 'function') {
						errcb()
					} else {
						appcan.window.openToast('GPS定位超时！', 1000, 5);
					}
				}
			}, appcfg.set.outime);
			uexLocation.onChange = function(lat, lng) {
				if (!hasLocat) {
					return
				}
				clearTimeout(chaoshi);
				hasLocat = null;
				chaoshi = null;
				appcan.ls.val('gps', JSON.stringify({
					lat: lat,
					lng: lng
				}));
				uexLocation.closeLocation();
				appcan.loading.hide();
				typeof(callback) === 'function' && callback(lat, lng);
			}
			uexLocation.openLocation();
		}
	};
	//日期天数计算:timeCalculator(new Date(),-15);
	var timeCalculator = function(date, day) {
		var nowms = Date.parse(date.toString());
		var dayms = day * 1000 * 60 * 60 * 24;
		var result = new Date(nowms + dayms);
		//console.log(result)
		return result;
	};

	//浮点数乘法
	function _accMul(arg1, arg2) {
		var m = 0,
			s1 = arg1.toString(),
			s2 = arg2.toString();
		try {
			m += s1.split(".")[1].length;
		} catch (e) {}
		try {
			m += s2.split(".")[1].length;
		} catch (e) {}
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
	};

	module.exports = {
		sendMsg: _sendMsg,
		logout: _logout,
		secMobile: _secMobile,
		initUser: _initUser,
		getUser: _getUser,
		proCounter: _proCounter,
		preGet: _preGet,
		checkPreget: _checkPreget,
		source: _source,
		getDate: _getDate,
		checkUpdate: _checkUpdate,
		jpush: _catchPush,
		richMedia: _richMedia,
		xss: _xss,
		uploadifyLocation: _uploadifyLocation,
		openBaiduMap: _openBaiduMap,
		commonTemp: _commonTemp,
		getAddrByLoc: _getAddrByLoc,
		getLocation: _getLocation,
		collection: _collection,
		accMul: _accMul
	}
});